package com.xq.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.xq.pojo.Configuration;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xiaoqiang
 * @Description:
 * @Date: 2021/5/28
 * @Version: 1.0
 */

public class XmlConfiguration {
    Logger logger = Logger.getLogger(XmlConfiguration.class);
    Configuration configuration;

    public XmlConfiguration() {
        configuration = new Configuration();
    }

    /**
     * 解析xml
     *
     * @param in
     * @return
     */
    public Configuration xml2Config(InputStream in) throws DocumentException, PropertyVetoException, SAXException {
        logger.info("解析数据库配置文件开始---------------");
        Document document = new SAXReader().read(in); //读取到xml
        Element root = document.getRootElement(); //获取跟节点
        List<Element> list = root.selectNodes("//property"); //  "//"表示再任何位置都可以查到
        Map<String, String> map = new HashMap<>(10);
        for (Element element : list) {
            //获取property标签中的name，value属性
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            map.put(name, value);
        }
        //利用c3p0创建数据库连接源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(map.get("driverClass"));
        dataSource.setJdbcUrl(map.get("jdbcUrl"));
        dataSource.setUser(map.get("username"));
        dataSource.setPassword(map.get("password"));
        configuration.setDataSource(dataSource);
        logger.info("解析数据库配置文件结束---------------");

        logger.info("解析sql文件开始---------------");

        List<Element> sqlListElement = root.selectNodes("//mapper");
        for (Element element : sqlListElement) {
            String resource = element.attributeValue("resource");
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(resource);
        }

        return configuration;
    }
}
